<template>
  <div class="low-code-preview" style="display: flex;flex-direction: column;gap: 10px;">
    <div  v-for="(component, index) in config" :key="index">
      <!-- 基础输入组件 -->
      <el-input
        v-if="component.type === 'input'"
        v-model="previewData[component.config.prop]"
        v-bind="getComponentProps(component)"
        :placeholder="component.config.placeholder"
      />
      
      <!-- 文本域 -->
      <el-input
        v-else-if="component.type === 'textarea'"
        v-model="previewData[component.config.prop]"
        type="textarea"
        v-bind="getComponentProps(component)"
        :placeholder="component.config.placeholder"
      />
      
      <!-- 数字输入框 -->
      <el-input-number
        v-else-if="component.type === 'number'"
        v-model="previewData[component.config.prop]"
        v-bind="getComponentProps(component)"
      />
      
      <!-- 选择器 -->
      <el-select
        v-else-if="component.type === 'select'"
        v-model="previewData[component.config.prop]"
        v-bind="getComponentProps(component)"
        :placeholder="component.config.placeholder"
      >
        <el-option
          v-for="option in component.config.options"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      
      <!-- 日期选择器 -->
      <el-date-picker
        v-else-if="component.type === 'date'"
        v-model="previewData[component.config.prop]"
        v-bind="getComponentProps(component)"
        :placeholder="component.config.placeholder"
      />
      
      <!-- 开关 -->
      <el-switch
        v-else-if="component.type === 'switch'"
        v-model="previewData[component.config.prop]"
        v-bind="getComponentProps(component)"
      />
      
      <!-- 搜索区域 -->
      <el-card v-else-if="component.type === 'search'" class="search-card">
        <div class="filter-header">
          <div class="filter-title">搜索条件</div>
          <div class="filter-actions">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
        
        <common-form
          ref="searchFormRef"
          v-model="searchFormData"
          :form-fields="generateSearchFields(component)"
          :label-width="component.config.labelWidth"
          :gutter="20"
          class="filter-form"
        />
      </el-card>
      
      <!-- 表格区域 -->
      <el-card v-else-if="component.type === 'table'" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">数据列表</div>
            <div class="table-actions">
              <el-button type="primary" @click="handleAdd">新增</el-button>
              <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">
                批量删除
              </el-button>
            </div>
          </div>
        </template>
        
        <common-table
          :table-data="component.data.data"
          :table-columns="component.data.columns"
          :show-selection="component.config.showSelection"
          :show-index="component.config.showIndex"
          :show-pagination="true"
          :pagination="pagination"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #actions="{ row }">
            <el-button size="small" type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </common-table>
      </el-card>
      
      <!-- 表单区域 -->
      <common-dialog
        v-else-if="component.type === 'form'"
        v-model="dialogVisible"
        :title="dialogTitle"
        :confirm-loading="dialogLoading"
        @confirm="handleDialogConfirm"
        @cancel="handleDialogCancel"
        width="600px"
      >
        <common-form
          ref="formRef"
          v-model="formModel"
          :form-fields="generateFormFields(component)"
          :label-width="component.config.labelWidth"
        />
      </common-dialog>
      
      <!-- 自定义按钮 -->
      <el-button
        v-else-if="component.type === 'custom-button'"
        v-bind="getCustomComponentProps(component)"
      >
        {{ component.config.label }}
      </el-button>
      
      <!-- 自定义卡片 -->
      <el-card
        v-else-if="component.type === 'custom-card'"
        v-bind="getCustomComponentProps(component)"
      >
        <template #header v-if="component.config.header">
          <div class="card-header">
            {{ component.config.header }}
          </div>
        </template>
        {{ component.config.content || '自定义卡片内容' }}
      </el-card>
      
      <!-- 图表区域 -->
      <el-card v-else-if="component.type === 'chart'" class="chart-card">
        <div 
          :id="`chart-${component.id}`" 
          class="chart-container"
          :style="{ height: component.config.height || '400px' }"
        ></div>
      </el-card>
      
      <!-- 默认占位符 -->
      <div v-else class="component-placeholder">
        <p>组件预览: {{ component.type }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUpdated, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CommonForm from '@/components/CommonForm.vue'
import CommonTable from '@/components/CommonTable.vue'
import CommonDialog from '@/components/CommonDialog.vue'
import * as echarts from 'echarts'
import 'echarts-gl' // 用于3D图表支持

const props = defineProps({
  config: {
    type: Array,
    required: true
  }
})

// 预览数据
const previewData = reactive({})

// 表单引用
const searchFormRef = ref()
const formRef = ref()

// 搜索表单数据
const searchFormData = reactive({})

// 表单数据模型
const formModel = reactive({})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50]
})

// 已选中的行
const selectedRows = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const dialogLoading = ref(false)
const dialogType = ref('add') // add 或 edit

// 计算属性 - 弹窗标题
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增' : '编辑'
})

// 监听配置变化，更新预览数据
watch(() => props.config, (newConfig) => {
  // 初始化预览数据
  newConfig.forEach(component => {
    if (component.config && component.config.prop) {
      previewData[component.config.prop] = component.config.defaultValue || ''
    }
  })
}, { immediate: true })

// 获取组件属性
const getComponentProps = (component) => {
  const props = { ...component.config }
  // 移除不必要的属性
  delete props.prop
  delete props.label
  delete props.placeholder
  delete props.options
  return props
}

// 获取自定义组件属性
const getCustomComponentProps = (component) => {
  const props = {}
  if (component.config.customProps) {
    component.config.customProps.forEach(prop => {
      if (prop.key && prop.value) {
        props[prop.key] = prop.value
      }
    })
  }
  return props
}

// 生成搜索字段
const generateSearchFields = (component) => {
  // 查找所有基础组件并生成搜索字段
  const searchFields = []
  for (const item of props.config) {
    if (['input', 'select', 'date', 'switch'].includes(item.type)) {
      searchFields.push({
        prop: item.config.prop,
        label: item.config.label,
        type: item.type,
        placeholder: item.config.placeholder,
        options: item.config.options,
        attrs: item.config.attrs
      })
    }
  }
  return searchFields
}

// 生成表单字段
const generateFormFields = (component) => {
  // 查找所有基础组件并生成表单字段
  const formFields = []
  for (const item of props.config) {
    if (['input', 'textarea', 'number', 'select', 'date', 'switch'].includes(item.type)) {
      formFields.push({
        prop: item.config.prop,
        label: item.config.label,
        type: item.type,
        placeholder: item.config.placeholder,
        options: item.config.options,
        attrs: item.config.attrs
      })
    }
  }
  return formFields
}

// 搜索事件
const handleSearch = () => {
  ElMessage.success('执行搜索操作')
}

// 重置搜索条件
const handleReset = () => {
  searchFormRef.value?.resetFields()
}

// 添加
const handleAdd = () => {
  dialogType.value = 'add'
  // 重置表单数据
  Object.keys(formModel).forEach(key => {
    formModel[key] = ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 填充表单数据
  Object.keys(formModel).forEach(key => {
    formModel[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除该条数据吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条数据吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('批量删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

// 弹窗确认
const handleDialogConfirm = async () => {
  try {
    await formRef.value?.validate()
    dialogLoading.value = true
    
    // 模拟异步提交
    setTimeout(() => {
      dialogLoading.value = false
      dialogVisible.value = false
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
    }, 1000)
  } catch (error) {
    // 验证失败
  }
}

// 弹窗取消
const handleDialogCancel = () => {
  formRef.value?.resetFields()
}

// 表格选择事件
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  ElMessage.info(`每页显示 ${val} 条`)
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  ElMessage.info(`当前第 ${val} 页`)
}

// 图表实例映射
const chartInstances = new Map()

// 在组件挂载后初始化图表
onMounted(() => {
  initCharts()
})

// 在组件更新后重新渲染图表
onUpdated(() => {
  renderCharts()
})

// 在组件卸载前销毁图表
onUnmounted(() => {
  destroyCharts()
})

// 初始化图表
const initCharts = () => {
  props.config.forEach(component => {
    if (component.type === 'chart') {
      const chartDom = document.getElementById(`chart-${component.id}`)
      if (chartDom) {
        const chartInstance = echarts.init(chartDom)
        chartInstances.set(component.id, chartInstance)
      }
    }
  })
  renderCharts()
}

// 渲染图表
const renderCharts = () => {
  props.config.forEach(component => {
    if (component.type === 'chart') {
      const chartInstance = chartInstances.get(component.id)
      if (chartInstance && component.config.option) {
        let option
        try {
          // 如果option是字符串，则尝试解析为JSON
          if (typeof component.config.option === 'string') {
            option = JSON.parse(component.config.option)
          } else {
            option = component.config.option
          }
          chartInstance.setOption(option, true)
        } catch (e) {
          console.error('图表配置解析错误:', e)
        }
      }
    }
  })
}

// 销毁图表
const destroyCharts = () => {
  chartInstances.forEach(chart => {
    chart.dispose()
  })
  chartInstances.clear()
}

</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.filter-title {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.table-card {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.chart-card {
  margin-top: 20px;
}

.chart-container {
  width: 100%;
}

.component-placeholder {
  padding: 20px;
  text-align: center;
  background-color: #f5f7fa;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  margin-bottom: 10px;
}
</style>